package com.estar.integaration.Util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

    static Logger logger = LoggerFactory.getLogger(Util.class);


    //判断是全0的一行，也就意味着结束了。
    public static Boolean isAllZeroArray(Integer[] arr){
      int length =  arr.length;
      for(int i = 0; i < length; i++){
        if(arr[i] == 1)
          return false;
      }
      return true;
    }

  /**
   * 将两个String类型的数字加起来返回一个String
   *
   * @param strNum1
   * @param strNum2
   * @return
   */
  public static String add2StringIntegerValue(String strNum1,String strNum2){
      Integer n1 = Integer.parseInt(strNum1);
      Integer n2 = Integer.parseInt(strNum2);
      Integer res = n1 + n2;
      return String.valueOf(res);
    }

  /**
   * 将两个String类型的数字加起来返回一个String
   * @param strNum1
   * @param strNum2
   * @return
   */
  public static String minus2StringIntegerValue(String strNum1,String strNum2){
    Integer n1 = Integer.parseInt(strNum1);
    Integer n2 = Integer.parseInt(strNum2);
    Integer res = n1 - n2;
    return String.valueOf(res);
  }

    /**
     * 写入文件到本地
     * @param multipartFile
     *                    内容有：
     *                    1 technologyDepartment 技术部
     *                    2 productionDepartmet 生产部
     *                    3 purchaseDepartment 采购部
     */
    public static String writeFile2Local(MultipartFile multipartFile,String environment,String name){
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String fileName = "";
        String department = "technologyDepartment";
        try {
            inputStream = multipartFile.getInputStream();
            fileName = multipartFile.getOriginalFilename();  //获得原始名
            logger.info(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = "";
        if(environment.equals("dev")){
          path = "D:\\SCM_file\\purchaseProcess\\test";
        }else if(environment.equals("prod") || environment.equals("prodB")){
          path = "/" + "root" + "/" + "excel" + "/"  + department;
        }
       // 测试用
//        String path = "D:\\SCM_file\\purchaseProcess\\test";
        byte[] bs = new byte[1024];
        int len;
        File tmpFile = new File(path);
        if(!(tmpFile.exists())){
            tmpFile.mkdirs();
        }
        try {
            outputStream = new FileOutputStream(tmpFile.getPath() + "/" + name + ".xlsx");
            while ((len = inputStream.read(bs)) != -1){
                outputStream.write(bs,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tmpFile.getPath() + File.separator + name + ".xlsx";  //返回地址 TODO 这里要自定义
    }

  /**
   * 写文件到本地
   * @param multipartFile
   * @param path
   */
    public static String writePaymentFile2Local(MultipartFile multipartFile ,String path){
      InputStream inputStream = null;
      OutputStream outputStream = null;
      String fileName = "";
      try {
        inputStream = multipartFile.getInputStream();
        fileName = multipartFile.getOriginalFilename();  //获得原始名
        logger.info(fileName);
      } catch (IOException e) {
        e.printStackTrace();
      }
      // 测试用
      byte[] bs = new byte[1024];
      int len;
      //新建文件夹
      File tmpFile = new File(path);
      if(!(tmpFile.exists())){
        tmpFile.mkdirs();
      }
      try {
        outputStream = new FileOutputStream(tmpFile.getPath() + "/" + fileName);
        while ((len = inputStream.read(bs)) != -1){
          outputStream.write(bs,0,len);
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }finally {
        try {
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      return tmpFile.getPath() + File.separator + fileName;  //返回地址
    }


    //写文件到本地
    public static String writeInventoryFile2Local(MultipartFile multipartFile,String environment,String fileFolder){
      InputStream inputStream = null;
      OutputStream outputStream = null;
      String fileName = null;
      try {
        inputStream = multipartFile.getInputStream();
        fileName = multipartFile.getOriginalFilename();
        logger.info(fileName);
      }catch (IOException e){
        e.printStackTrace();
      }
      String path = "";
      if(environment.equals("dev")){
        path = "D:\\SCM_file\\inventoryFile\\" + fileFolder;
      }else if(environment.equals("prod") || environment.equals("prodB")){
        path = "/" + "root" + "/" + "excel" + "/" + "inventoryFile/"  + fileFolder;
      }
      byte[] bs = new  byte[1024];
      int len = 0;
      File tmpFile = new File(path);
      if(!tmpFile.exists()){
        tmpFile.mkdirs();
      }
      try {
        outputStream = new FileOutputStream(tmpFile.getPath() + "/" + fileName);
        while ((len = inputStream.read(bs)) != -1){
          outputStream.write(bs,0,len);
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }finally {
        try {
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      return tmpFile.getPath() + File.separator + fileName + ".xlsx";
    }





    public static void deleteAllFile(File folder){
      if(!folder.exists()){
        return;
      }
      if(!folder.isDirectory()){
        return;
      }
      File[] files = folder.listFiles();
      for(File f : files){
        f.delete();
      }
    }


    /**获得一个文件夹下所有文件的文件路径**/
    public static List<String> getAllFilePathName(String path){
        List<String> nameList = new ArrayList<>();
        File fileDir = new File(path);

        if(fileDir.isDirectory()){
            File fileList[] = fileDir.listFiles();
            for(int i = 0 ; i < fileList.length ; i++){
                if(fileList[i].isDirectory()){
                    nameList.addAll(getAllFilePathName(fileList[i].getPath()));
                }
                else {
                    nameList.add(path + "\\" +fileList[i].getName());
                }
            }
        }
        return nameList;
    }

    /**通过FileNmae创建文件返回文件名**/
    public static String createNewFile(String fileName) throws IOException {
        File file = new File("C:" + File.separator + "FeatureDir");
        if(!file.exists()){
            file.mkdir();
        }
        BufferedWriter bw=new BufferedWriter(new FileWriter(file.getPath() + File.separator + fileName));
        bw.write("");
        bw.close();
        return file.getAbsolutePath() + File.separator + fileName;
    }

    /**
     * 把byte[] 转换成String
     * @param b
     * @return
     */
    public static String byteArray2String(byte [] b){

        String str = Base64.getEncoder().encodeToString(b);

        return str;
    }

    /**
     * 把String转成byte[]
     * @param str
     * @return
     */
    public static byte[] string2ByteArray(String str){

        byte[] ba = {};
        ba = Base64.getDecoder().decode(str);
        return ba;
    }


  /**
   * 取出-出现次数
   * @param s
   * @return
   */
    public static int getCharacterTiems(String s){
        int length = s.length();
        String tmp = s.replace("-","");
        int tmpLength = tmp.length();
        return length - tmpLength;
    }

  /**
   * 比较日期大小
   * @return
   */
  public static boolean compareDate(String d1,String d2){
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {
      Date dt1 = df.parse(d1);//将字符串转换为date类型
      Date dt2 = df.parse(d2);
      if(dt1.getTime()>dt2.getTime())//比较时间大小,如果dt1大于dt2
      {
        return true;
      }
      else
      {
        return false;//运行输出no
      }
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return false;//无法比较输出false
  }


  /**
   * 回传
   * @param file
   * @return
   */
  public static ResponseEntity<FileSystemResource> exportExcel(File file){
    if(file == null){
      return null;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "attachment; filename=" + file.getName());
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    headers.add("Last-Modified", new Date().toString());
    headers.add("ETag", String.valueOf(System.currentTimeMillis()));
    return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
  }


  /**
   * 获得UUId
   */
  public static String getUUID(){
    return UUID.randomUUID().toString().toUpperCase().replace("-","");
  }

    /**
     * 字符串判断是否有特殊字符
     * @param str
     * @return true/false
     * @Author HLF
     */
  public static boolean isSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

}
